﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Collections;
using System.Text.RegularExpressions;
using System.Web;
using System.Threading;
using System.Xml;

namespace IYAA_BBS_SPIDER
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
        }
        string domain = System.Configuration.ConfigurationSettings.AppSettings["domain"].ToString();
        int selectIndex = -1;
        string url = string.Empty;
        string formhash = string.Empty;
        string posttime = string.Empty;
        CookieContainer cc;
        Thread th;

        #region 跨线程访问控件

        /// <summary>
        /// 在richTextBox上追加文本
        /// </summary>
        /// <param name="text"></param>
        private void rTextBox(string text)
        {
            SetText(text + " - " + DateTime.Now.ToLongTimeString() + "\r\n");
        }
        private delegate void MyInvoke(string txt);
        private void SetText(string s)
        {
            try
            {
                if (richTextBox1.InvokeRequired)
                {
                    MyInvoke _myInvoke = new MyInvoke(SetText);
                    this.Invoke(_myInvoke, new object[] { s });
                }
                else
                {
                    this.richTextBox1.AppendText(s);
                    this.richTextBox1.ScrollToCaret();
                }
            }
            catch { }
        }


        #endregion

        /// <summary>
        /// Login AND Analyze
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            if (toolStripButton1.Text == @"登陆")
            {
                Thread loginTh = new Thread(new ThreadStart(AdminLogin));
                loginTh.IsBackground = true;
                loginTh.Start();
            }
            else if (toolStripButton1.Text == @"分析")
            {

                Thread analyzeTh = new Thread(new ThreadStart(StartAnalyze));
                analyzeTh.IsBackground = true;
                analyzeTh.Start();

            }

        }

        /// <summary>
        /// Load
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {

            //listView1.CheckBoxes = true;//设置listView1的复选框属性为真
            //listView1.View = View.Details;//设置listView1的视图方式
            //listView1.GridLines = true;//设置listView1显示网格线
            listView1.Columns.Add("标题", 388, HorizontalAlignment.Left);//向listView1中添加“Title”列
            listView1.Columns.Add("地址", 300, HorizontalAlignment.Left);//向listView1中添加“Address”列


            //combobox
            toolStripComboBox1.Items.Add("科技新闻");//0
            toolStripComboBox1.Items.Add("本地新闻");//1
            toolStripComboBox1.Items.Add("社会新闻");//2
            toolStripComboBox1.Items.Add("体育新闻");//3
            toolStripComboBox1.Items.Add("时尚爱美");//4
            toolStripComboBox1.Items.Add("家居装修");//5
            toolStripComboBox1.Items.Add("健康养生");//6
            toolStripComboBox1.Items.Add("苗条淑女");//7
            toolStripComboBox1.Items.Add("育儿专家");//8
            toolStripComboBox1.Items.Add("美食分享");//9
            toolStripComboBox1.Items.Add("地方特产");//10
            toolStripComboBox1.Items.Add("房产信息");//11
            toolStripComboBox1.Items.Add("招聘/求职");//12
            toolStripComboBox1.Items.Add("恋爱征婚");//13
            toolStripComboBox1.Items.Add("生活服务");//14
            toolStripComboBox1.Items.Add("创业投资");//15
            toolStripComboBox1.Items.Add("心情分享吧");//16
            toolStripComboBox1.Items.Add("哎呀图吧");//17
            toolStripComboBox1.Items.Add("游戏竞技");//18
            toolStripComboBox1.Items.Add("搞笑频道");//19
            toolStripComboBox1.Items.Add("娱乐杂志");//20

            //SelectedIndex
            toolStripComboBox1.SelectedIndex = 0;

        }

        /// <summary>
        /// ALL
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked == true)
            {
                SelectAll();
            }
            else
            {
                UnSelectAll();
            }
        }

        /// <summary>
        /// 复制标题
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 复制标题ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems[0].Text != "")
                Clipboard.SetDataObject(listView1.SelectedItems[0].Text);
            //rTextBox("复制标题:" + listView1.SelectedItems[0].Text);
        }

        /// <summary>
        /// 复制地址
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 复制地址ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems[0].Tag.ToString() != "")
                Clipboard.SetDataObject(listView1.SelectedItems[0].Tag);
            //rTextBox("复制地址:" + listView1.SelectedItems[0].Tag);
        }

        /// <summary>
        /// UnSelectAll
        /// </summary>
        private void UnSelectAll()
        {
            foreach (ListViewItem tempItem in listView1.Items)//循环遍历listView控件中的每一项
            {
                if (tempItem.Checked)//如果当前项处于选中状态
                {
                    tempItem.Checked = false;//设置当前项为未选中状态
                }
            }
        }

        /// <summary>
        /// SelectAll
        /// </summary>
        private void SelectAll()
        {
            foreach (ListViewItem tempItem in listView1.Items)//循环遍历listView控件中的每一项
            {
                if (tempItem.Checked == false)//如果当前项处于未选中状态
                {
                    tempItem.Checked = true;//设置当前项为选中状态
                }
            }
        }

        /// <summary>
        /// GetSelectItems
        /// </summary>
        /// <returns></returns>
        public ArrayList GetSelectItems()
        {
            ArrayList list = new ArrayList();
            foreach (ListViewItem tempItem in listView1.CheckedItems)//循环遍历listView控件中的每一项
            {
                list.Add(tempItem);

            }

            return list;
        }

        /// <summary>
        /// Analyze html,add items to listView1
        /// </summary>
        private void StartAnalyze()
        {
            rTextBox("开始分析");
            toolStripStatusLabel1.Text = "开始分析..";
            selectIndex = toolStripComboBox1.SelectedIndex;
            string title = string.Empty;
            string address = string.Empty;

            //start update listview1
            listView1.Items.Clear();
            listView1.BeginUpdate();

            if (selectIndex == 0)
            {
                url = @"http://www.cnbeta.com";
                string html = Html.GetNewInstnce().GetResponseString(url);
                MatchCollection res = new Regex("(?<=<dt class=\\\"topic\\\" >)[\\s\\S]*?(?=<dd class=\\\"author\\\">)").Matches(html);
                foreach (Match m in res)
                {
                    title = new Regex("(?<=<strong>)[^<]*?(?=</strong>)").Matches(m.ToString())[0].ToString();
                    address = @"http://www.cnbeta.com" + new Regex("(?<=<a href=\\\")[^>]*?(?=\\\")").Matches(m.ToString())[0].ToString();

                    ListViewItem OptionItem = new ListViewItem(title);
                    OptionItem.SubItems.Add(address);
                    OptionItem.Tag = address;
                    listView1.Items.Add(OptionItem);
                }
                //end update listview1
                listView1.EndUpdate();
            }
            rTextBox("分析完成");
            toolStripStatusLabel1.Text = "分析完成!";
            System.Threading.Thread.CurrentThread.Abort();
        }

        /// <summary>
        /// login
        /// </summary>
        private void AdminLogin()
        {
            toolStripStatusLabel1.Text = "正在登陆中..";
            rTextBox("正在登陆");
            toolStripButton1.Enabled = false;
            ArrayList returnList = new ArrayList();
            try
            {
                //get base cookies
                ArrayList getBaseDate = Html.GetNewInstnce().GetHtmlData(domain + @"portal.php", new CookieContainer());
                //login
                ArrayList list = Html.GetNewInstnce().PostData(@"formhash=0ec39474&referer=http%3A%2F%2Fwww.iyaa.cn%2Fportal.php&loginfield=username&username=admin&password=3313453&questionid=0&answer=&loginsubmit=true", @"http://www.iyaa.cn/member.php?mod=logging&action=login&loginsubmit=yes&frommessage&loginhash=L6Z96&inajax=1", (CookieContainer)getBaseDate[0]);
                //tops page
                ArrayList getdate = Html.GetNewInstnce().GetHtmlData(domain + @"forum.php?mod=post&action=newthread&fid=2&referer=http%3A//www.iyaa.cn/forum.php%3Fmod%3Dviewthread%26tid%3D5%26extra%3D", (CookieContainer)list[0]);
                if (getdate.Count >= 1)
                {
                    returnList.Add(getdate[0]);
                    cc = (CookieContainer)getdate[0];
                }
                formhash = new Regex("(?<=<input type=\\\"hidden\\\"[^>]*?name=\\\"formhash\\\"[^>]*?value=\\\")[\\w]*?(?=\\\")").Matches(getdate[1].ToString())[0].ToString();
                if (!string.IsNullOrEmpty(formhash))
                {
                    returnList.Add(formhash);
                }
                posttime = new Regex("(?<=<input type=\\\"hidden\\\"[^>]*?name=\\\"posttime\\\"[^>]*?value=\\\")[\\w]*?(?=\\\")").Matches(getdate[1].ToString())[0].ToString();
                if (!string.IsNullOrEmpty(posttime))
                {
                    returnList.Add(posttime);
                }
            }
            catch (Exception ex)
            {
                returnList = null;
                rTextBox(ex.Message);
            }
            if (returnList != null)
            {
                if (returnList.Count == 3)
                {
                    rTextBox("登陆成功");
                    this.Text = @"IYAA.CC - 登陆成功";
                    toolStripButton1.Enabled = true;
                    toolStripButton1.Text = @"分析";
                    toolStripStatusLabel1.Text = "登陆成功!";
                }
            }
            else
            {
                rTextBox("登陆失败");
                this.Text = @"IYAA.CC - 登陆失败";
                toolStripButton1.Enabled = true;
                toolStripStatusLabel1.Text = "登陆失败,请从新登陆!";
            }
            System.Threading.Thread.CurrentThread.Abort();


        }

        /// <summary>
        /// GO
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            if (button1.Text == "采集")
            {

                rTextBox("开始采集选中内容");
                button1.Text = "暂停";
                th = new Thread(new ThreadStart(SendTopic));
                th.IsBackground = true;
                th.Start();
            }
            else if (button1.Text == "暂停")
            {
                rTextBox("采集暂停");
                button1.Text = "继续";
                th.Suspend();
            }
            else if (button1.Text == "继续")
            {
                rTextBox("采集继续");
                button1.Text = "暂停";
                th.Resume();
            }
        }

        /// <summary>
        /// 获得选中的帖子发出去
        /// </summary>
        public void SendTopic()
        {
            string title = string.Empty;
            string url = string.Empty;
            string html = string.Empty;
            string content = string.Empty;
            StringBuilder postData = new StringBuilder();

            ArrayList list = GetSelectItems();
            if (list == null)
            {

            }
            if (list.Count == 0)
            {

            }
            foreach (ListViewItem item in list)
            {
                try
                {
                    rTextBox("正在采集:" + item.Text);

                    title = item.Text;
                    url = item.Tag.ToString();
                    html = Html.GetNewInstnce().GetResponseString(url);

                    Regex regMatchContent = new Regex("(<div id=\\\"news_content\\\">)[\\s\\S]*?(?=<div class=\\\"digbox\\\">)");
                    string result = regMatchContent.Matches(html)[0].ToString() + @"</div>";
                    content = Html.GetNewInstnce().DoHtmlToUBB(result);

                    title = HttpUtility.UrlEncode(item.Text, Encoding.GetEncoding("gb2312"));
                    content = HttpUtility.UrlEncode(content, Encoding.GetEncoding("gb2312"));

                    //%5Bimg%5Dhttp%3A%2F%2Fimages.weiphone.com%2Fattachments%2FDay_121015%2F0_2537775_70ac6945ea26044.jpg%5B%2Fimg%5D

                    postData.Append("formhash=" + formhash);
                    postData.Append("&posttime=" + posttime);
                    postData.Append("&wysiwyg=1");
                    postData.Append("&subject=" + title);
                    postData.Append("&message=" + content);
                    postData.Append("&romotepic=1");//本地化远程图片
                    postData.Append("&replycredit_extcredits=0");
                    postData.Append("&replycredit_times=1");
                    postData.Append("&replycredit_membertimes=1");
                    postData.Append("&replycredit_random=100");
                    postData.Append("&readperm=");
                    postData.Append("&price=");
                    postData.Append("&tags=");
                    postData.Append("&rushreplyfrom=");
                    postData.Append("&rushreplyto=");
                    postData.Append("&rewardfloor=");
                    postData.Append("&stopfloor=");
                    postData.Append("&creditlimit=");
                    postData.Append("&save=");
                    postData.Append("&usesig=1");
                    postData.Append("&allownoticeauthor=1");
                    


                    //发帖步骤
                    ArrayList postTopic = Html.GetNewInstnce().PostData(postData.ToString()
                        , @"http://www.iyaa.cn/forum.php?mod=post&action=newthread&fid=2&extra=&topicsubmit=yes", cc);

                    //@"formhash=" + formhash + @"&posttime=" + posttime
                    //    + @"&wysiwyg=1&subject=" + title + @"&message=" + content
                    //    + @"&replycredit_extcredits=0&replycredit_times=1&replycredit_membertimes=1&replycredit_random=100&readperm=&"
                    //    + @"price=&tags=&rushreplyfrom=&rushreplyto=&rewardfloor=&stopfloor=&creditlimit=&save=&usesig=1&allownoticeauthor=1"

                }
                catch (Exception ex)
                {

                    rTextBox(ex.Message);
                }

                rTextBox("完成");
            }

            rTextBox("所有选中条目已采集完成");
            toolStripStatusLabel1.Text = "完成";
            System.Threading.Thread.CurrentThread.Abort();


        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            string xmlStr = string.Empty;

            XmlHelper.EditXmlAttr("xml/images.xml", "root", "imgUrl", "html", "http://iyaa.cc/view/index91653.html");


            //xmlStr = xmlStr;







            //string url;
            //string img;
            //XmlElement xe;

            //XmlDocument xmlDoc = new XmlDocument();
            //xmlDoc.Load("xml/images.xml");
            //XmlNode xn = xmlDoc.SelectSingleNode("root");

            //XmlNodeList xnl = xn.ChildNodes;

            //foreach (XmlNode xnf in xnl)
            //{
            //    xe = (XmlElement)xnf;
            //    url = xe.GetAttribute("url");//显示属性值 
            //    img = xe.GetAttribute("imageUrl");


            //} 
        }








    }
}
